package com.studyspringcloud.product.control;

import com.studyspringcloud.product.VO.ProductInfoVO;
import com.studyspringcloud.product.VO.ProductVO;
import com.studyspringcloud.product.VO.ResultVO;
import com.studyspringcloud.product.model.ProductCategory;
import com.studyspringcloud.product.model.ProductInfo;
import com.studyspringcloud.product.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    /**
     * 查询在架的商品，
     * 获取type列表
     * 查询类目
     * 构造数据
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResultVO list(){
        List<ProductInfo> list = productService.findUpAll();
        List<Integer> typeList = list.stream().map(ProductInfo::getType).collect(Collectors.toList());

        List<ProductCategory> categories = productService.findByTypeIn(typeList);
        List<ProductVO> results = new ArrayList<>();
        for(ProductCategory category : categories){
            ProductVO vo = new ProductVO();
            vo.setName(category.getName());
            vo.setType(category.getType());
            List<ProductInfoVO> infoVOS = new ArrayList<>();
            for(ProductInfo info : list){
                if(info.getType().equals(category.getType())) {
                    ProductInfoVO infoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(info, infoVO);
                    infoVOS.add(infoVO);
                }
            }
            vo.setProductInfoVOList(infoVOS);
            results.add(vo);
        }
        return ResultVO.suceess(results);
    }
    @RequestMapping("/getProductInfoById")
    @ResponseBody
    public ResultVO  getProductInfoById(Integer id){
        ProductInfo info =  productService.findInfoById(id);
        ProductInfoVO vo = new ProductInfoVO();
        BeanUtils.copyProperties(info,vo);
        return ResultVO.suceess(vo);
    }

    @RequestMapping("/findCategoryById")
    @ResponseBody
    public ResultVO  findCategoryById(Integer id){
        ProductCategory category =  productService.findCategoryById(id);
        return ResultVO.suceess(category);
    }
}
